# coding=utf-8
import os
import re
import sys
import traceback

import akshare as ak
import pandas
import pandas as pd
from loguru import logger

from models.stock_model import StockNumber, DayInfo
from mylib.download_all import analysis_stock
from mylib.mycsv import sort_csv


def run(d=1):
    if d:
        sz_index_df = ak.index_zh_a_hist(symbol="000001", period="daily")
        df_sorted = sz_index_df.sort_values(by='日期', ascending=False)
        df_sorted.to_csv("shanghai_index.csv", index=False)
    else:
        df_sorted = pd.read_csv('shanghai_index.csv')
    today_date = eval(str(list(df_sorted['日期'])[0]).replace('-', ''))
    return today_date


def get_3down_len(today_date, sn, N):
    """
    获取N次跌幅大于3时间长短
    """
    sc = f'stocks/{sn.ts_code}.csv'
    if not os.path.exists(sc):
        return None, None, None, None
    df = pandas.read_csv(sc)
    if str(df['trade_date'][0]) != str(today_date):
        analysis_stock(sn)
        df = pandas.read_csv(sc)
    d_arr = []
    today_d = None
    days_len = 0
    down_N = 0
    for row in df.index:
        d = DayInfo(sn, df.loc[row])
        if today_d is None:
            today_d = d
        if row == 0 and (d.pct_chg > 0 or d.close < 5):
            return None, None, None, None
        if down_N == row and d.pct_chg <= 0:
            down_N += 1
        if d.pct_chg <= -3:
            d_arr.append(d)
        if len(d_arr) >= N:
            days_len = row
            break
    res = re.findall('stocks/(.*).csv', sc)
    link_code_arr = res[0].split('.')
    link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
    hyperlink = f'"https://xueqiu.com/S/{link_code}"'
    date_arr_hyp = f'=HYPERLINK({hyperlink})'
    return today_d, days_len, date_arr_hyp, down_N


def get_all_stock_csv_path():
    for root, dirs, files in os.walk('stocks'):
        return [os.path.join(root, item) for item in files]


if __name__ == '__main__':
    # 获取最近N次跌幅大于3耗时的距离排序
    N = 6
    while N > 2:
        N -= 1
        D = True
        today_date = run(D)
        full_path_tk = f'{today_date}_3over_N{N}.csv'
        f_tk = open(full_path_tk, 'w', encoding='utf-8')
        f_tk.write(f'行业,名称,distance,cur_down,当前价格,涨跌幅,连接')
        df = pd.read_csv('cal_ops/all.csv')
        full_path_txt = f'{today_date}_get_3over_N{N}.txt'
        if os.path.exists(full_path_txt):
            os.remove(full_path_txt)
        logger.add(full_path_txt, format='{message}')
        n_arr = []
        ts_code_arr = []
        result_dict = {}
        for row in df.index:
            sn = StockNumber(df.loc[row])
            logger.info(f'N={N} {sn.name}')
            if 'ST' in sn.name:
                continue
            # if sn.name not in [
            #     '骏亚科技',
            # ]:
            #     continue
            try:
                today_d, max_len, date_arr_hyp, down_N = get_3down_len(today_date, sn, N)
                if today_d is None and max_len is None and max_len is None:
                    continue
                rhs_pct = round(today_d.pct_chg, 2)
                w_msg = f'\n{sn.industry},{sn.name},{max_len},{down_N},{today_d.close},{rhs_pct},{date_arr_hyp}'
                f_tk.write(w_msg)
                f_tk.flush()
            except Exception as e:
                print(e, traceback.format_exc())
        if os.path.exists(full_path_txt):
            os.remove(full_path_txt)
        f_tk.close()
        sort_csv(full_path_tk, ['distance', '行业', 'cur_down'], [True, True, False])
